package com.merck.service.readfbu;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.merck.service.export.SqlStr;
import com.merck.service.impl.ImportData;
import com.merck.service.impl.ImportDataServiceImpl;
import com.merck.service.readparameter.ExcelReaderUtil;
import com.merck.service.readparameter.ReadParameter;
import com.merck.utils.DateUtils;
import com.merck.utils.JDBCUtils;
import com.merck.utils.SendMail;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Properties;

/**
 * @program: export_flow
 * @description: 读fub
 * @author: Lucas
 * @create: 2021-04-20 17:28
 **/
public class ReadFbuImpl {
    private Logger log = Logger.getLogger(ReadParameter.class);

    public void run() {
        System.out.println("开始导入数据-----------");
        AmazonS3 s3Client = null;
        Properties pro = new Properties();
        InputStream resourceAsStream = null;
        InputStream in = null;
        try {
            System.out.println("读取配置文件开始-----------");
            resourceAsStream = ReadParameter.class.getResourceAsStream("/db.properties");
            pro.load(resourceAsStream);
            System.out.println("读取配置文件结束-----------");
        } catch (Exception e) {
            System.out.println("读取配置文件异常-----------");
            log.error(e.getMessage());
        } finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());

                }
            }
        }


        //S3获取文件夹下所有的文件
        System.out.println("读取S3下的文件-----------");
        ImportData importData = new ImportDataServiceImpl();
        String bucketName = (String) pro.get("bucket.fbu");
        String path = (String) pro.get("remote.fbu");
        //备份路径
        String dateStr ="fbu"+ DateUtils.format(new Date(), "yyyyMMddHHmmss");
        String backBucketName = (String) pro.get("back.bucket.fbu");
        String backPath = (String) pro.get("back.remote.fbu") + dateStr + "/";
        s3Client = openS3ClientByEC2();
//        ListObjectsV2Result result = s3Client.listObjectsV2(bucketName, path);
//
//
        System.out.println("读取S3下的文件结束-----------");
////
        Connection connection = null;
        System.out.println("准备循环文件流-----------");
        System.out.println();
        System.out.println("开启JDBC----------");
        FileOutputStream downloadFile = null;
        try {
            connection = JDBCUtils.getConnection();
            //清空表数据；
            String delSql = "truncate lego_kpi_calculation.stg_kpi_fbu_hco_list";
            PreparedStatement state = connection.prepareStatement(delSql);
            state.execute();

            File file;
            //备份
            System.out.println("源桶：----"+bucketName);
            System.out.println("源健：-----"+path);
            System.out.println("目标桶：-----"+backBucketName);
            System.out.println("目标健：-----"+backPath);
            s3Client.copyObject(bucketName, path, backBucketName, backPath + "kpi_fbu_hco_master.xlsx");

            //获取要导入的文件
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
            S3Object s3Object = s3Client.getObject(getObjectRequest);
            in = s3Object.getObjectContent();
            //            写入文件
            int index;
            byte[] bytes = new byte[1024];
            downloadFile = new FileOutputStream("temp.xlsx");
            while ((index = in.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            in.close();
            downloadFile.flush();
            FileChannel channel = downloadFile.getChannel();
            channel.force(true);
            FileDescriptor fd = downloadFile.getFD();
            fd.sync();
            downloadFile.close();
            file = new File("temp.xlsx");
            System.out.println("执行导入操作-----------");
            //备份excel
            ExcelReaderUtil.readExcel(importData, "temp.xlsx", "lego_kpi_calculation.stg_kpi_fbu_hco_list", connection);
            file.delete();
            log.info("导入当前excel表格成功");
//            }
            System.out.println("关闭JDBC----------");
            connection.close();
            System.out.println("导入excel表格成功-----------");
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导入数据任务在 " + currentDateAsString + " 运行结果通知", SqlStr.SUCESS_SEND_CONTENT, null);
            log.info("导入excel表格成功");
        } catch (Exception e) {
//            String currentDateAsString = DateUtils.getCurrentDateAsString();
//            SendMail.sendMail(null, null, "导入数据任务在 " + currentDateAsString + " 运行结果通知", SqlStr.FAILURE_SEND_CONTENT, null);
            log.error(e.getMessage());
            throw new RuntimeException("导入数据失败:" + e.getMessage());
        }finally {
            try {
                if (downloadFile != null) {

                    downloadFile.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());

            }
        }
        //S3获取文件夹下所有的文件-结束



    }


    public static AmazonS3 openS3ClientByEC2() {
        AmazonS3 s3Client = null;
        try {
            s3Client = AmazonS3ClientBuilder.defaultClient();
        } catch (Exception e) {
            throw new RuntimeException("获取S3客户端失败" + e.getMessage());
        }
        return s3Client;
    }


}
